# python
# coding=utf-8

'''
  自动为MarkDown标题编号

  title_sn.py demo.md
  
  demo.md    --->   demo.md
  ---------
  # A				# 1 A
  ## aa				## 1.1 aa
  ### aaa				### 1.1.1 aaa
  ### bbb				### 1.1.2 bbb
  ## bb				## 1.2 bb
  ### aaa				### 1.2.1 aaa
  ### bbb				### 1.2.2 bbb
  # B				# 2 B
  ## bb				## 2.1 bb
  ### aaa				### 2.1.1 aaa
  ### bbb				### 2.1.2 bbb
'''


import sys
import os
import os.path
import re

rootdir="./"

# for parent,dirnames,filenames in os.walk(rootdir):
# 	for dirname in  dirnames:                  
# 		print "parent is:" + parent
# 		print  "dirname is" + dirname

# 	for filename in filenames:
# 		print filename


def zero():
    return "zero"
 
def one():
    return "one"
def is_headline(line):
	head=["#","##","###","####","#####","######"]
	# print "fff",line
	# s = "## 3.2 fgh1ijk"
	# print line
	L=line.split(' ')
	# print L[0], L[1], L[2]
	
	if 0 == cmp(head[0],L[0]):
		# print 1
		return 1

	if 0 == cmp(head[1],L[0]):
		# print 2
		return 2
	if 0 == cmp(head[2],L[0]):
		# print 3
		return 3
	if 0 == cmp(head[3],L[0]):
		# print 4
		return 4
	if 0 == cmp(head[4],L[0]):
		# print 4
		return 5
	# print 0
	return 0

# def is_index(line)
def is_index(line):
	head=['0','1','2','3','4','5','6','7','8','9','.']
	L=line.split(' ')

	len_list= len(L)

	if len_list < 2:
		return 0

	strlen=len(L[1])
	for index in L[1]:
		find=0
		for h in head:
			# print h, index
			if h == index:
				find=1
		if find==0:
			return False
	# print line
	return True

def is_code(line):
	len_list= len(line)
	if len_list >= 3:
		if line[0] == line[1] == line[2] == '`':
			return True
	return False

def help():
	print 'title.py [in file]'

if __name__ == '__main__':

	if len(sys.argv) < 1:
		help()
		exit(0)

	ifile=sys.argv[1]
	# ofile=sys.argv[2]
	filename=ifile
	ro = open(filename, 'r')
	

	# float_number="12.a 2.222"
	# value = re.compile(r'^[-+]?[0-9]+\.[0-9]+$')
	# value = re.compile(r'[0-9]+\.[0-9]?(2)+$')
	# value = re.compile(r'^(?=.*[.])(?=.*[0-9]).*$')
	# result = value.match(float_number)
	# if result:
	#     print "Number is a float."

	# else:
	#     print "Number is not a float."

	head=["#","##","###","####", "#####"]
	H1=0
	H2=0
	H3=0
	H4=0
	H5=0
	codeflag=0
	tcontext = []
	while True:
		line = ro.readline()
		if not line:
			break

		# 过滤掉 "``` ```"之间的代码注释
		if True == is_code(line):
			codeflag = codeflag ^1
		if codeflag == 1:
			# fw.write(line)
			tcontext.append(line)
			continue


		Hn=is_headline(line)
		L=line.split(' ')

		if Hn != 0:
			if Hn==1:
				H1+=1;H2=0;H3=0;H4=0;
				index_str = "%d" %(H1)
			if Hn==2:
				H2+=1;H3=0;H4=0;
				index_str = "%d.%d" %(H1, H2)
			if Hn==3:
				H3+=1;H4=0;
				index_str = "%d.%d.%d" %(H1, H2, H3)
			if Hn==4:
				H4+=1;
				index_str = "%d.%d.%d.%d" %(H1, H2, H3, H4)
			if Hn==5:
				H5+=1;
				index_str = "%d.%d.%d.%d.%d" %(H1, H2, H3, H4, H5)
			


			if True == is_index(line):
				if len(L) > 2:
					print (head)
					tcontext.append('%s %s'  % (head[Hn-1], index_str))

					for i in L[2::]:
						tcontext.append(' %s' %i )
						print i


			else:
				tcontext.append('%s %s' % (head[Hn-1], index_str))
				for i in L[1::]:
					tcontext.append(' %s' %i )
					print i
		else:
			tcontext.append(line)

	ro.close()

	fw = open(ifile, 'w')
	for line in tcontext:
		fw.write(line)
	fw.close()
